iT邦幫忙

0

[C#] 兩數之和解法

c#
  • 分享至 

  • xImage
  •  

Example 1:

Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Explanation: Because nums[0] + nums[1] == 9, we return [0, 1].
Example 2:

Input: nums = [3,2,4], target = 6
Output: [1,2]
Example 3:

Input: nums = [3,3], target = 6
Output: [0,1]

下方為 Example 1 解法

       static void Main(string[] args)
       {
           TwoSum();
       }

       private static void TwoSum()
       {
           var nums = new int[] { 2, 7, 11,15};
           int target = 9;
           var result = TwoSum(nums, target);
           Console.WriteLine($"目標索引:{result[0]},{result[1]}");
           Console.ReadKey();
       }

       /// <summary>
       /// 兩數之和
       /// </summary>
       /// <param name="nums">數組</param>
       /// <param name="target">目標值</param>
       /// <returns></returns>
       private static int[] TwoSum(int[] nums, int target)
       {
           int left = 0;
           int right = nums.Length - 1;
           while(left < right)
           {
               int sum = nums[left] + nums[right];
               if(sum == target)
               {
                   return [left, right];
               }
               else if(sum < target)
               {
                   left++;
               }
               else if (sum > target)
               {
                   right--;
               }
           }
           return [ -1, -1 ];
       }

圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言